//
//  RCOAuthController.swift
//  RC-微博0305
//
//  Created by 任淳 on 16/3/7.
//  Copyright © 2016年 ReverChun. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class RCOAuthController: UIViewController {

    let RCWebView = UIWebView()
    
    //返回上一个控制器方法
    func goBack() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //测试账号用户名和密码的设置
    func testNum() {
        let str = "document.getElementById('userId').value = '18050087500',document.getElementById('passwd').value = 'renCHUN58598393'"
        //JavaScript执行字符串 修改名称和密码
        RCWebView.stringByEvaluatingJavaScriptFromString(str)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //把view换成webView
        view = RCWebView
        
        RCWebView.delegate = self
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "goBack")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "testNum")
        
        loadWebView()
        
    }

    //加载webView
    func loadWebView() {
        /*
        App Key：491856493
        App Secret：c1c4720029c3a44df154b5a3e5d84d3a
        */
        
        //加载到登录微博页面的urlStr 授权登录
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=491856493" + "&redirect_uri=http://www.baidu.com"
        
        let url = NSURL(string: urlStr)
        
        let request = NSURLRequest(URL: url!)
        
        RCWebView.loadRequest(request)
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(true)
        
        SVProgressHUD.dismiss()
    }
    
  }



//实现webView的代理方法 遵守webView协议
extension RCOAuthController:UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //一般协议方法 返回值 为 bool类型 默认返回yes  想对应的控件就能够正常工作 反之  不能正常工作
    //在这个协议方法中 可以监测到webView每次加载新的页面发起的网络请求
    //这个方法可以拦截发送的请求 并且中断访问 不加载数据
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //在这里想办法拿到code 用code最终获取token
        //print(request.URL)18050087500
        print("absoluteString == \(request.URL?.absoluteString)")
        print("======")
        print("query == \(request.URL?.query)")
        
        guard let String = request.URL?.absoluteString else {
            return false
        }
        
        if String.containsString("code") {

            guard let query = request.URL?.query else {
                return false
            }
            let str = "code="
            let code = (query as NSString).substringFromIndex(str.characters.count)
//            print(code)
            //得到code后 用code获取token
            RCUserModel.sharedUserModel.getToken(code, finish: { (isSucceed) -> () in
                //回调 如果成功了
                if isSucceed {
                 //用户信息加载好以后 就跳转到欢迎页 ==============================第一次跳转
                    NSNotificationCenter.defaultCenter().postNotificationName("chooseController", object: "WelcomePage")
                    
                    
                }else {
                    //失败了
                    SVProgressHUD.showErrorWithStatus("格式装换失败")
                    
                }
                
                
            })
        
            return false
        }
        return true
    }

    
    
}
